package utils;

import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WriteException;

import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by asus on 2017/6/20.
 */
public class ExcelUtils {

    /**
     * 设置excel表头
     *
     * @param headersInfo
     * @param sheet
     */
    public static void outputHeaders(String[] headersInfo, WritableSheet sheet) throws WriteException {
        Label label = null;
        //创建列头
        for (int i = 0; i < headersInfo.length; i++) {
            label = new Label(i, 0, headersInfo[i]);
            sheet.addCell(label);
        }
    }

    /**
     * 获取表内容
     * @param headersInfo 表头数组
     * @param columnsInfo 每一行的List集合
     * @param sheet  excel的一张sheet表
     * @param rowIndex  暂时没有用到
     * @throws WriteException
     */
    public static void outputColumns(String[] headersInfo, List columnsInfo, WritableSheet sheet, int rowIndex) throws WriteException {
        Label label = null;
        int headerSize = headersInfo.length;
        int columnSize = columnsInfo.size();
        System.out.println("outputColumns" + columnsInfo);
        //循环插入多少行
        for (int i = 1; i <= columnsInfo.size(); i++) {
            Object obj = columnsInfo.get(i - 1);
            //循环每行多少列
            for (int j = 0; j < headersInfo.length; j++) {
                Object value = getFieldValueByName(headersInfo[j], obj);
                label = new Label(j, i, value.toString());
                sheet.addCell(label);
            }
        }
    }

    /**
     * 根据对象的属性获取值
     *
     * @param fieldName
     * @param obj
     * @return
     * @author David
     */
    private static Object getFieldValueByName(String fieldName, Object obj) {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        try {
            Method method = obj.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(obj, new Object[]{});
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("属性不存在！");
            return null;
        }
    }

}
